//
//  ViewModelType.swift
//  myhub
//
//  Created by x on 2024/3/6.
//

import Foundation
import RxCocoa
import RxSwift
import XNetwork
import XLog

public protocol ViewModelType {
    associatedtype Input
    associatedtype Output

    func transform(input: Input) -> Output
}

open class ViewModel: NSObject {
    
    open var page = 1

    public let loading = ActivityIndicator()
    public let headerLoading = ActivityIndicator()
    public let footerLoading = ActivityIndicator()

    public let error = ErrorTracker()
    public let serverError = PublishSubject<ApiError>()
    public let parsedError = PublishSubject<ApiError>()

    public override init() {
        super.init()
        serverError.asObservable().map { (error) -> ApiError? in
            do {
                let errorResponse = error as? XMoyaError
                if let body = errorResponse?.response?.data,
                   let errorResponse = try? JSONDecoder().decode(ErrorResponse.self, from: body) {
                    return ApiError.serverError(response: errorResponse)
                }
            }
            return nil
        }.filterNil().bind(to: parsedError).disposed(by: rx.disposeBag)

        parsedError.subscribe { (error) in
            logError("\(error)")
        }.disposed(by: rx.disposeBag)
    }

    deinit {
        logDebug("\(type(of: self)): Deinited")
        logResourcesCount()
    }
}
